package com.credithc.fastdfs.api.util;

import org.apache.commons.lang.StringUtils;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public class UserAgentUtil {

	private final static String EXT_NAME_JPG="jpg|jpeg|jpe";
	private final static String EXT_NAME_PNG="png";
	private final static String EXT_NAME_GIF="gif";
	private final static String EXT_NAME_PDF="pdf";
	private final static String EXT_NAME_HTML="htm|html";
	private final static String OPENTYPE_DOWNLOAD="download";

	/**
	 *
	 * <br>描 述：获取客户端浏览器类型、编码下载文件名
	 * <br>作 者：zj
	 * <br>历 史: (版本) 作者 时间 注释
	 * @param request
	 * @param fileName
	 * @return
	 */
	public static String encodeFileName(HttpServletRequest request, String fileName) {
		String userAgent = request.getHeader("User-Agent");
		return encodeFileName(userAgent, fileName);
	}
	/**
	 *
	 * <br>描 述：获取客户端浏览器类型、编码下载文件名
	 * <br>作 者：zj
	 * <br>历 史: (版本) 作者 时间 注释
	 * @param request
	 * @param fileName
	 * @return
	 */
	public static String encodeFileName(String userAgent, String fileName) {
		String rtn = "";
		try {
			String new_filename = URLEncoder.encode(fileName, "UTF8");
			// 如果没有UA，则默认使用IE的方式进行编码，因为毕竟IE还是占多数的
			rtn = "filename=\"" + new_filename + "\"";
			if (userAgent != null) {
				userAgent = userAgent.toLowerCase();
				// IE浏览器，只能采用URLEncoder编码
				if (userAgent.indexOf("msie") != -1) {
					rtn = "filename=\"" + new_filename + "\"";
				}
				// Opera浏览器只能采用filename*
				else if (userAgent.indexOf("opera") != -1) {
					rtn = "filename*=UTF-8''" + new_filename;
				}
				// Safari浏览器，只能采用ISO编码的中文输出
				else if (userAgent.indexOf("safari") != -1) {
					rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
				}
				// Chrome浏览器，只能采用MimeUtility编码或ISO编码的中文输出
				else if (userAgent.indexOf("applewebkit") != -1) {
					new_filename = MimeUtility.encodeText(fileName, "UTF8", "B");
					rtn = "filename=\"" + new_filename + "\"";
				}
				// FireFox浏览器，可以使用MimeUtility或filename*或ISO编码的中文输出
				else if (userAgent.indexOf("mozilla") != -1) {
					rtn = "filename*=UTF-8''" + new_filename;
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return rtn;
	}

	/**
	 *
	 * <br>描 述：设置response的相关header、mime
	 * <br>作 者：zj
	 * <br>历 史: (版本) 作者 时间 注释
	 * @param request
	 * @param response
	 * @param fileName
	 * @param length
	 */
	public static void setHeaders(HttpServletResponse response,String userAgent,String orgFileName,long length,String openType){
		String mime="application/octet-stream; charset=utf-8";
		String extName=getExtensionName(orgFileName).toLowerCase();

		if(StringUtils.endsWithIgnoreCase(openType, OPENTYPE_DOWNLOAD)){
			response.setHeader("Content-disposition", "attachment;" + encodeFileName(userAgent, orgFileName));
		}else{
			if(EXT_NAME_JPG.indexOf(extName)>-1){
				mime="image/jpeg";
			}else if(EXT_NAME_PNG.indexOf(extName)>-1){
				mime="image/png";
			}else if(EXT_NAME_GIF.indexOf(extName)>-1){
				mime="image/gif";
			}else if(EXT_NAME_GIF.indexOf(extName)>-1){
				mime="image/gif";
			}else if(EXT_NAME_PDF.indexOf(extName)>-1){
				mime="application/pdf";
				response.setHeader("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline';");
			}else if(EXT_NAME_HTML.indexOf(extName)>-1){
				mime="text/html; charset=utf-8";
			}else{
				response.setHeader("Content-disposition", "attachment;" + encodeFileName(userAgent, orgFileName));
			}
		}

		if(length>0){
			response.setHeader("Content-Length", String.valueOf(length));
		}
		response.setContentType(mime);
	}

	protected static String getExtensionName(String fileName) {
        if ((fileName != null) && (fileName.length() > 0)) {
            int dot = fileName.lastIndexOf('.');
            if ((dot >-1) && (dot < (fileName.length() - 1))) {
                return fileName.substring(dot + 1);
            }
        }
        return fileName;
    }
}
